package cn.wolfcode.service.impl;

import cn.wolfcode.domain.Role;
import cn.wolfcode.mapper.RoleMapper;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.service.IRoleService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * ClassName RoleServiceImpl
 * Create by Mike
 * Date 2021/8/1 16:46
 */
@Service
@Transactional
@Setter
@Slf4j
public class RoleServiceImpl implements IRoleService {

    @Autowired
    private RoleMapper roleMapper;

    private IPermissionService permissionService;

    @Override
    public void save(Role role,Long[] permissionIds) {
        //除了往角色表添加数据
        roleMapper.insert(role);
        //还要往中间表role_permission插入数据
        saveRelation(role, permissionIds);
    }

    @Override
    public void delete(Long id) {
        roleMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void update(Role role,Long[] permissionIds) {
        roleMapper.updateByPrimaryKey(role);
        //如何修改中间表role_permission中的数据
        //先删除中间表role_permission中此角色的权限数据
        roleMapper.deleteRelation(role.getId());
        //再往中间表role_permission中保存信息关系数据
        saveRelation(role, permissionIds);
    }

    @Override
    public Role get(Long id) {
        return roleMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Role> listAll() {
        return roleMapper.selectAll();
    }

    @Override
    public PageInfo<Role> query(QueryObject qo) {

        //使用分页插件,传入当前页,每页显示数量
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize());

        List<Role> roles = roleMapper.selectForList(qo);

        return new PageInfo(roles);
    }

    @Override
    public List<Role> queryByEmployeeId(Long employeeId) {
        return roleMapper.selectByEmployeeId(employeeId);
    }

    private void saveRelation(Role role, Long[] permissionIds) {
        if (permissionIds != null && permissionIds.length > 0) {
            for (Long permissionId : permissionIds) {
                roleMapper.insertRelation(role.getId(), permissionId);
            }
        }
    }
}
